package cn.iocoder.yudao.module.hs.netty;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.iocoder.yudao.module.hs.dal.dataobject.device.DeviceDO;
import cn.iocoder.yudao.module.hs.service.device.DeviceService;
import io.netty.channel.Channel;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
public class Transmission {

    @Getter
    private static Map<String, Channel> channelMap = new TreeMap<>();

    @Getter
    private static Map<String, LocalDateTime> channelExpireTimeMap = new TreeMap<>();

    @Getter
    private static Map<Long, Set<String>> warehouseDeviceMap = new TreeMap<>();

    public static void addChannel(String deviceId, Channel channel) {
        channelMap.put(deviceId, channel);
        channelExpireTimeMap.put(deviceId, LocalDateTime.now());
        DeviceService deviceService = SpringUtil.getApplicationContext().getBean(DeviceService.class);
        DeviceDO device = deviceService.getDeviceByCode(deviceId);
        if (device != null) {
            if (warehouseDeviceMap.containsKey(device.getWarehouseId())) {
                warehouseDeviceMap.get(device.getWarehouseId()).add(deviceId);
            } else {
                Set<String> deviceIdSet = new HashSet<>();
                deviceIdSet.add(deviceId);
                warehouseDeviceMap.put(device.getWarehouseId(), deviceIdSet);
            }
        }
//        log.info("基站心跳：{}", deviceId);
//        log.info("设备列表：{}", channelMap.keySet());
//        log.info("连接过期时间详情：{}", channelExpireTimeMap.entrySet().stream()
//                .map(entry -> "设备ID: " + entry.getKey() + ", 过期时间: " + entry.getValue())
//                .collect(Collectors.toList()));
//        log.info("仓库设备映射详情：{}", warehouseDeviceMap.entrySet().stream()
//                .map(entry -> "仓库ID: " + entry.getKey() + ", 设备IDs: " + entry.getValue())
//                .collect(Collectors.toList()));

    }

    public static void removeChannel(String deviceId) {
        channelMap.remove(deviceId);
        channelExpireTimeMap.remove(deviceId);
        Iterator<Long> iterator = warehouseDeviceMap.keySet().iterator();
        while (iterator.hasNext()) {
            Long warehouseId = iterator.next();
            warehouseDeviceMap.get(warehouseId).remove(deviceId);
            if (CollUtil.isEmpty(warehouseDeviceMap.get(warehouseId))) {
                iterator.remove();
            }
        }
    }

}
